const axios = require('axios');
const inquirer = require('inquirer');
const ora = require('ora');


// 工具方法：添加耗时等待
const addLoading = function (fn) {

    return async function (...args) {
        const spinner = ora('拉取开始....');
        spinner.start();
        try {
            let ret = await fn(...args);
            spinner.succeed('拉取成功')
            return ret;
        } catch (error) {
            console.log(error)
            spinner.fail('拉取失败');
        }
    }

}
// 工具方法：获取仓库列表
const fetchRepoList = async function () {
    const { data } = await axios.get('https://api.github.com/users/zcegg/repos')
    const repos = data.map(item => item.name)
    return repos;
}

// 工具方法：获取 tags 列表
const fetchTagList = async function (tmpname) {
    const { data } = await axios.get(`https://api.github.com/repos/zcegg/${tmpname}/tags`)
    const repos = data.map(item => item.name)
    return repos;
}



module.exports = async (pramas) => {

    // 获取模板列表
    const repos = await addLoading(fetchRepoList)();

    // 交互问题
    let { tmpname } = await inquirer.prompt({
        type: 'list',
        name: 'tmpname',
        message: '请选择目标仓库模板',
        choices: repos,
    })
    console.log(tmpname);

    // 拉取 tags ， tags可能为有值数组或空数组
    const tags = await addLoading(fetchTagList)(tmpname);

    console.log(tags);


    // tags分支处理 [v1,v2,v3.....]  []
    if (tags.length) {
        // 仓库存在多个tag
        let { tagv } = await inquirer.prompt({
            type: 'list',
            name: 'tagv',
            message: '请选择目标版本',
            choices: tags,
        })
        console.log(tagv);
    } else {
        //  仓库不存在多个 tags 版本
        let { isDownload } = await inquirer.prompt({
            type: 'confirm',
            name: 'isDownload',
            message: '当前不存在多个tag是否直接下载',
        })

        if (isDownload) {
            console.log('选择yes直接执行下载操作');
        } else {
            return;
        }
    }


}


